package com.epalmpay.service.ys.shop.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.epalmpay.entity.*;
import com.epalmpay.mapper.*;
import com.epalmpay.mapper.profit.ProfitGroupMonthMapper;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.epalmpay.exception.ApplicationException;
import com.epalmpay.status.Rescode;
import com.epalmpay.dto.yunliu.shop.YsShopInDTO;
import com.epalmpay.dto.yunliu.shop.YsShopListOutDTO;
import com.epalmpay.dto.yunliu.shop.YsShopOutDTO;
import com.epalmpay.enumdef.CommonEnum;
import com.epalmpay.enumdef.BizEnum.UserStatus;
import com.epalmpay.payplat.IPayAPI;
import com.epalmpay.payplat.MerchantRegister;
import com.epalmpay.payplat.MerchantUpdate;
import com.epalmpay.payplat.PayBalanceQuery;
import com.epalmpay.payplat.result.PayBalanceResult;
import com.epalmpay.payplat.result.PayResult;
import com.epalmpay.service.weixin.IWalletService;
import com.epalmpay.service.ys.shop.IYsShopService;
import com.epalmpay.util.Const;
import com.epalmpay.util.HttpClientUtil;
import com.epalmpay.util.PropertyCopyUtil;
import com.epalmpay.util.StringUtil;
import com.epalmpay.util.Tools;
import com.epalmpay.util.payplat.UtilFun;

@Service("ysShopService")
public class YsShopServiceImpl implements IYsShopService{
	
	@Resource
	private ShopMapper shopMapper;
	
	@Resource
	private GroupMapper groupMapper;
	
	@Resource
	private UserbaseMapper userbaseMapper;
	
	@Resource
	private ShopGroupRelationMapper shopGroupRelationMapper;
	@Resource
	private YsShopCarMapper ysShopCarMapper;

	@Resource
	private AgentMapper agentMapper;

	@Resource
	private ProfitGroupMonthMapper profitGroupMonthMapper;

	@Resource
	private IWalletService walletService;

	@Override
	public YsShopListOutDTO shopList(YsShopInDTO shopInDTO, Page page) throws Exception {
		YsShopListOutDTO shopListOutDTO = new YsShopListOutDTO();
		
		Map<String,Object> param=new HashMap<String,Object>();
//		param.put("groupId",shopInDTO.getGroupId());
		if (shopInDTO.getKeyWord()!=null) {
			if ("安装".equals(shopInDTO.getKeyWord())) {
				param.put("isInstall", 1);
			}
			if ("改装".equals(shopInDTO.getKeyWord())) {
				param.put("isRefit", 1);
			}
			if ("美容".equals(shopInDTO.getKeyWord())) {
				param.put("isCosmetology", 1);
			}
			if ("维修".equals(shopInDTO.getKeyWord())) {
				param.put("isRepair", 1);
			}
			if ("保养".equals(shopInDTO.getKeyWord())) {
				param.put("isMaintain", 1);
			}
		}
		param.put("groupId",shopInDTO.getGroupId());
		param.put("agentId",shopInDTO.getAgentId());
		param.put("agentLevel",shopInDTO.getAgentLevel());
		param.put("subIndustry",shopInDTO.getSubIndustry());
		param.put("lastLoginStart", shopInDTO.getLastLoginStart());
		param.put("lastLoginEnd", shopInDTO.getLastLoginEnd());
		param.put("shopType", shopInDTO.getShopType());
		param.put("agentName",shopInDTO.getAgentName());
		param.put("shopName",shopInDTO.getShopName());
		param.put("status",shopInDTO.getShopStatus());

		int sumCount = shopMapper.selectYsShopCount(param);
		page.setTotalResult(sumCount);
		if(sumCount<=0)
			return shopListOutDTO;
		
		param.put("limit", page.getShowCount());
		param.put("start", page.getShowCount()*(page.getCurrentPage()-1));
		
		List<YsShopOutDTO> shopList = shopMapper.selectYsShopList(param);
		shopListOutDTO.setYsShopOutDTOList(shopList);
		
		return shopListOutDTO;
	}

	@Override
	public Shop findShopStatus(Long id) throws Exception {
		return shopMapper.findShopStatus(id);
	}

	@Override
	public void updateStatus(Shop shop) throws Exception {
//		shopMapper.updateStatus(shop);
		shopMapper.updateByPrimaryKeySelective(shop);
	}


	@Override
	public Boolean saveshop(YsShopInDTO shopInDTO) throws ApplicationException {
		 //根据地址查询经纬度
		  String detailed=shopInDTO.getProvinceCityDistrict()+shopInDTO.getAddress();
		  String result=HttpClientUtil.get(Const.GEOCODER+detailed);
		  JSONObject jsonObj= JSONObject.parseObject(result);
		  Object statusObject=jsonObj.get("status");
		  Integer status=Integer.parseInt(String.valueOf(statusObject)); 
			  if(status.equals(0)){
				  //根据groupId查询大商户
				  Group group=groupMapper.selectByPrimaryKey(shopInDTO.getGroupId());
				  JSONObject resultObject=jsonObj.getJSONObject("result");
			//	  String title=resultObject.getString("title");
				  JSONObject address_componentsObject=resultObject.getJSONObject("address_components");//地址详细信息
				  JSONObject locationObject=resultObject.getJSONObject("location");//经纬度对象
				  String province=address_componentsObject.getString("province");
				  String city=address_componentsObject.getString("city");
				  String district=address_componentsObject.getString("district");
				  Double lng=locationObject.getDouble("lng");
				  Double lat=locationObject.getDouble("lat");
				  Userbase userbase=new Userbase();
				  userbase.setBz("大商户创建门店");
				  userbase.setGmtCreate(new Date());
				  userbase.setGmtModified(new Date());
				  userbase.setGroupId(shopInDTO.getGroupId());
				  userbase.setIp(null);
				  userbase.setLastLogin(null);
				  userbase.setPassword(new SimpleHash("SHA-1", shopInDTO.getUsername(), shopInDTO.getPassword()).toString());
				  userbase.setRights(null);//权限码默认为空
				  userbase.setRoleId("1");
				  userbase.setSkin("default");
				  userbase.setStatus(UserStatus.Stop.getType());//禁用
				  userbase.setUsername(shopInDTO.getUsername());
				  userbase.setUserType(CommonEnum.UserType.Store.getType());
				  userbaseMapper.insertKey(userbase);
					Shop shop = new Shop();
					shop.setMerchantName(shopInDTO.getMerchantName());//shopInDTO.getMerchantName()
					shop.setIndustry(shopInDTO.getIndustry());
					shop.setSubIndustry(51);
					shop.setPrincipalName(shopInDTO.getPrincipalName());
					shop.setPrincipalMobile(shopInDTO.getPrincipalMobile());
					shop.setPhone(shopInDTO.getPhone());
					shop.setWorkTime(shopInDTO.getWorkTime());
					shop.setIcon(shopInDTO.getQrImg());
					shop.setAddressProvince(province);// 省
					shop.setAddressCity(city);// 市
					shop.setAddressDistrict(district);// 区
					shop.setAddress(shopInDTO.getAddress());
					shop.setMemo(shopInDTO.getMemo());
					shop.setLongitude(lng+"");
					shop.setLatitude(lat+"");
					shop.setBusinessLicense(shopInDTO.getBusinessLicense());
					shop.setQrImg(shopInDTO.getQrImg());//null
					shop.setRecieveAccountType(shopInDTO.getRecieveAccountType());
					shop.setMerchantFeeId(shopInDTO.getMerchantFeeId());
					shop.setAccountBank(shopInDTO.getAccountBank());
					shop.setRecieveBankNo(shopInDTO.getRecieveBankNo());//收款卡号开户行支行
					shop.setRecieveBank(null);//收款银行
					shop.setRecieveName(shopInDTO.getRecieveName());
					shop.setUserId(userbase.getId());// 用户id 
					shop.setGmtModified(new Date());
//					shop.setStatus(1);
					shop.setStatus(0);
					shop.setGmtCreate(new Date());
					shop.setAccountArea(shopInDTO.getAccountArea());
					shop.setRecieveAccount(shopInDTO.getRecieveAccount()); 
					shop.setPersonId(shopInDTO.getPersonId());
					
					if (shopInDTO.getMainImg1()!=null) {
						
						if (shopInDTO.getMainImg2()!=null) {
							if (shopInDTO.getMainImg3()!=null) {
								if (shopInDTO.getMainImg4()!=null) {
									shop.setAlbumpics(shopInDTO.getMainImg1()+','+shopInDTO.getMainImg2()+','+shopInDTO.getMainImg3()+','+shopInDTO.getMainImg4()); 
								}else{
									shop.setAlbumpics(shopInDTO.getMainImg1()+','+shopInDTO.getMainImg2()+','+shopInDTO.getMainImg3()); 
								}
							}else{
								shop.setAlbumpics(shopInDTO.getMainImg1()+','+shopInDTO.getMainImg2()); 
							}
						}else{
							shop.setAlbumpics(shopInDTO.getMainImg1()); 
						}
					}else{
						shop.setAlbumpics(null);
					}
					try {
						shopMapper.insert(shop);
					} catch (Exception e) {
						throw new ApplicationException(Rescode.FAIL,"门店数据保存异常");
					}
					//门店与配置ys_shop_car关系
				  	Agent agent = new Agent();
					agent.setId(shopInDTO.getTagentId());
				  	YsShopOutDTO ysShopOutDTO = agentMapper.queryProfitAndPrprofit(agent);
				    YsShopCar ysShopCar = new YsShopCar();
				    ysShopCar.setShopId(shop.getId());
				  	ysShopCar.setGmtCreate(new Date());
				    ysShopCar.setGmtModified(new Date());
//				  	if(ysShopOutDTO.getFeeType()==0){
				    if(ysShopOutDTO!=null){
				    	ysShopCar.setPreprofitRate(ysShopOutDTO.getThirdPurchaseRate());//yucaigou
						ysShopCar.setProfitRate(ysShopOutDTO.getThirdFeeRate());//jiaoyi
						ysShopCar.setProfitUpdateTime(new Date());
						ysShopCar.setPreprofitUpdateTime(new Date());
						
				    }
						
//					}
				  try {
					  ysShopCarMapper.insertSelective(ysShopCar);
				  } catch (Exception e) {
					  throw new ApplicationException(Rescode.FAIL,"门店配置交易(预采购)分润保存异常");
				  }


				  String merName=shopInDTO.getMerchantName();//商户名称
					String corpType="02";// 00三资企业 01合资企业 02民营企业 03国企 04私营企业 
					String pubOrPri=null;
					String iDCardNo=null;
					String lineBankNum="000000000000";//支行联行号 
					String bankAccountNo=shopInDTO.getRecieveAccount();//结算银行卡号
					String bankAccountNm=shopInDTO.getRecieveName();
					String phone=shopInDTO.getPhone();
					String mobilePhone=shopInDTO.getPrincipalMobile();
					String groupId=group.getPayGroupCode();//大商户号 
					//String corpId=UtilFun.formatNumber(shop.getId(), 8);//商户唯一编号
					String corpId=UtilFun.createRandomStr(2)+UtilFun.formatNumber(shop.getId(), 6);
					String bankCode=shopInDTO.getAccountBank();//结算银行行号
					String sonBankName=Tools.notEmpty(shopInDTO.getRecieveBankNo())?shopInDTO.getRecieveBankNo():"default";//支行名称recieveBankNo
					//支行名称recieveBankNo
					Integer type=shopInDTO.getRecieveAccountType();
					String merLvl=shopInDTO.getMerchantFeeId();
					if(shopInDTO.getRecieveAccountType().equals(type)){
						pubOrPri="22";
						iDCardNo="000000000000000000";//长度必须是18位
					}else if(shopInDTO.getRecieveAccountType().equals(type)){
						pubOrPri="11";
						iDCardNo=shopInDTO.getPersonId();
					}
					MerchantRegister merchantRegister=MerchantRegister.initialize(
							corpId, merName, groupId, corpType, bankCode, 
							bankAccountNm, bankAccountNo, phone, mobilePhone, sonBankName,
							
							lineBankNum, pubOrPri, iDCardNo, merLvl, detailed);
					PayResult payResult=IPayAPI.merchantRegister(merchantRegister);
				    if(!PayResult.SUCCESS.equals(payResult.getRespCode())){
				    	throw new ApplicationException(Rescode.FAIL,payResult.getMsgTxt());
				    }
				    //创建门店-商户关系
					ShopGroupRelation shopGroupRelation=new ShopGroupRelation();
					shopGroupRelation.setGmtCreate(new Date());
					shopGroupRelation.setGmtModified(new Date());
					shopGroupRelation.setShopId(shop.getId());
					shopGroupRelation.setGroupId(shopInDTO.getGroupId());
					if(shopInDTO.getAgentId() ==null){
						shopGroupRelation.setAgentId(shopInDTO.getTagentId());//发展代理商ID
					}else {
						shopGroupRelation.setAgentId(shopInDTO.getAgentId());//发展代理商ID
					}
					shopGroupRelation.setPayMerchantCode(corpId);//支付平台商户号
					shopGroupRelation.setBalance(0L);
					shopGroupRelation.setLockBalanceEnc(new SimpleHash("SHA-1", "0", shopInDTO.getGroupId()+"").toString());//余额加密字段
					shopGroupRelation.setLockBalance(0L);
					shopGroupRelation.setLockBalanceEnc(new SimpleHash("SHA-1", "0", shopInDTO.getGroupId()+"").toString());//锁定金额密文
					shopGroupRelation.setVarturelCardno(null);//支付平台卡号 暂未返回
					shopGroupRelation.setType(1);
					shopGroupRelationMapper.insert(shopGroupRelation);
				
					return true;
			  }  else{
				  throw new ApplicationException(Rescode.FAIL,"地理位置解析异常");
				  
			  } 
	}

		@Override
		public YsShopOutDTO selectShopInfo(YsShopInDTO shopInDTO) throws ApplicationException {
			YsShopOutDTO shopOutDTO=new YsShopOutDTO();
			Shop shop=null;
			try {
			   shop=shopMapper.selectShopInfo(shopInDTO.getId(),shopInDTO.getGroupId());
			} catch (Exception e) {
				throw new ApplicationException(Rescode.FAIL,"查询详情异常");
			}
			try {
				PropertyCopyUtil.copyPropertiesExclude(shop, shopOutDTO);
			} catch (Exception e) {
				throw new ApplicationException(Rescode.FAIL,"属性复制异常");
			}
			shopOutDTO.setAgentName(shop.getAgent().getMerchantName());
			shopOutDTO.setTagentId(shop.getShopGroupRelation().getAgentId());
			shopOutDTO.setIndustryName(shop.getIndustryType().getName());
			shopOutDTO.setUserName(shop.getUserbase().getUsername()); 

			shopOutDTO.setMemberNum((shop.getStatisShop().getMemberNum()==null?0:shop.getStatisShop().getMemberNum()));

			shopOutDTO.setShopAddress(shop.getAddressProvince()+"/"+shop.getAddressCity()+"/"+shop.getAddressDistrict());

			//obd设备信息
			String UserId=shop.getShopGroupRelation().getPayMerchantCode()+"";
			
			String GroupId=shop.getGroup().getPayGroupCode();
		    
		    
		    Wallet wallet=walletService.selectShopWallet(UserId, GroupId, shop.getUserId());
		    shopOutDTO.setBalance(Long.valueOf(wallet.getCanBalance()));//余额 
		    shopOutDTO.setLockBalance(Long.valueOf(wallet.getCanFreezeBalance()));//锁定金额
		    
			shopOutDTO.setVarturelCardno(UserId);
			shopOutDTO.setAgentCreate(shop.getAgent().getGmtCreate());
			shopOutDTO.setAgentPhone(shop.getAgent().getPrincipalMobile());
			return shopOutDTO;
		}

		@Override
		public Boolean editShop(YsShopInDTO shopInDTO) throws ApplicationException {
			 //根据地址查询经纬度
			  String detailed=shopInDTO.getProvinceCityDistrict()+shopInDTO.getAddress();
			  String result=HttpClientUtil.get(Const.GEOCODER+"?="+detailed+"&key="+Const.MAP_KEY);
			  JSONObject jsonObj= JSONObject.parseObject(result);
			  Object statusObject=jsonObj.get("status");
			  Integer status=Integer.parseInt(String.valueOf(statusObject)); 
				  if(status.equals(0)){
					  //根据groupId查询大商户
					  Group group=groupMapper.selectByPrimaryKey(shopInDTO.getGroupId());
					  JSONObject resultObject=jsonObj.getJSONObject("result");
					  String title=resultObject.getString("title");
					  JSONObject address_componentsObject=resultObject.getJSONObject("address_components");//地址详细信息
					  JSONObject locationObject=resultObject.getJSONObject("location");//经纬度对象
					  String province=address_componentsObject.getString("province");
					  String city=address_componentsObject.getString("city");
					  String district=address_componentsObject.getString("district");
					  String lng=null;
					  String lat=null;
					  if(Tools.notEmpty(shopInDTO.getLongitude())&&Tools.notEmpty(shopInDTO.getLatitude())){
						  lng=shopInDTO.getLongitude();
						  lat=shopInDTO.getLatitude();
					  }else{
						  lng=locationObject.getDouble("lng")+"";
						  lat=locationObject.getDouble("lat")+"";
					  }

					  Shop shop=shopMapper.selectByPrimaryKey(shopInDTO.getId());
					  Userbase userbase=userbaseMapper.selectByPrimaryKey(shop.getUserId());
					  ShopGroupRelation shopGroupRelation=shopGroupRelationMapper.selectShopInfo(userbase.getGroupId(),shop.getId());
					  userbase.setBz("门店修改");
					  userbase.setGmtCreate(new Date());
					  userbase.setGmtModified(new Date());
					  userbase.setGroupId(shopInDTO.getGroupId());
					  userbase.setIp("");
					  userbase.setLastLogin(null);
					  if(Tools.notEmpty(shopInDTO.getPassword())){
						  userbase.setPassword(new SimpleHash("SHA-1", shopInDTO.getUsername(), shopInDTO.getPassword()).toString());
					  }
					  userbase.setRights("");//权限码默认为空
					  userbase.setRoleId("0");
					  userbase.setSkin("default");
					  userbase.setStatus(UserStatus.Normal.getType());
					  userbase.setUsername(shopInDTO.getUsername());
					  userbase.setUserType(CommonEnum.UserType.Store.getType());
					  userbase.setId(shop.getUserId()); 
					  userbaseMapper.updateByPrimaryKeySelective(userbase);
						shop.setMerchantName(shopInDTO.getMerchantName());//shopInDTO.getMerchantName()
						shop.setIndustry(shopInDTO.getIndustry());
					  	shop.setSubIndustry(51);
						shop.setPrincipalName(shopInDTO.getPrincipalName());
						shop.setPrincipalMobile(shopInDTO.getPrincipalMobile());
						shop.setPhone(shopInDTO.getPhone());
						shop.setWorkTime(shopInDTO.getWorkTime());
						shop.setIcon(shopInDTO.getIcon());
						shop.setAddressProvince(province);// 省
						shop.setAddressCity(city);// 市
						shop.setAddressDistrict(district);// 区
						shop.setAddress(shopInDTO.getAddress());
						shop.setMemo(shopInDTO.getMemo());
						shop.setLongitude(lng+"");
						shop.setLatitude(lat+"");
					    shop.setBusinessLicense(shopInDTO.getBusinessLicense());
						shop.setRecieveAccountType(shopInDTO.getRecieveAccountType());
						shop.setMerchantFeeId(shopInDTO.getMerchantFeeId());
						shop.setAccountBank(shopInDTO.getAccountBank());
						shop.setRecieveBankNo(shopInDTO.getRecieveBankNo());//收款卡号开户行支行
						shop.setRecieveBank(null);//收款银行
						shop.setRecieveName(shopInDTO.getRecieveName());
						shop.setUserId(userbase.getId());// 用户id 
						shop.setGmtModified(new Date());
						shop.setStatus(shop.getStatus());
						shop.setGmtCreate(shop.getGmtCreate());
						shop.setAccountArea(shopInDTO.getAccountArea());
						shop.setRecieveAccount(shopInDTO.getRecieveAccount()); 
						shop.setPersonId(shopInDTO.getPersonId());
						shop.setQrImg(shopInDTO.getQrImg());


						if (shopInDTO.getMainImg1()!=null) {
							
							if (shopInDTO.getMainImg2()!=null) {
								if (shopInDTO.getMainImg3()!=null) {
									if (shopInDTO.getMainImg4()!=null) {
										shop.setAlbumpics(shopInDTO.getMainImg1()+','+shopInDTO.getMainImg2()+','+shopInDTO.getMainImg3()+','+shopInDTO.getMainImg4()); 
									}else{
										shop.setAlbumpics(shopInDTO.getMainImg1()+','+shopInDTO.getMainImg2()+','+shopInDTO.getMainImg3()); 
									}
								}else{
									shop.setAlbumpics(shopInDTO.getMainImg1()+','+shopInDTO.getMainImg2()); 
								}
							}else{
								shop.setAlbumpics(shopInDTO.getMainImg1()); 
							}
						}
						
						try {
							shopMapper.updateByPrimaryKey(shop);
						} catch (Exception e) {
							throw new ApplicationException(Rescode.FAIL,"修改数据出现异常");
						}
						
						String merName=shopInDTO.getMerchantName();//商户名称 
						String corpType="02";// 00三资企业 01合资企业 02民营企业 03国企 04私营企业 
						String pubOrPri=null;
						String iDCardNo=null;
						String lineBankNum="000000000000";//支行联行号 
						String bankAccountNo=shopInDTO.getRecieveAccount();//结算银行卡号
						String bankAccountNm=shopInDTO.getRecieveName();
						String phone=shopInDTO.getPhone();
						String mobilePhone=shopInDTO.getPrincipalMobile();
						String groupId=group.getPayGroupCode();//大商户号 
						String corpId=shopGroupRelation.getPayMerchantCode();
						String bankCode=shopInDTO.getAccountBank();//结算银行行号
						String sonBankName=Tools.notEmpty(shopInDTO.getRecieveBankNo())?shopInDTO.getRecieveBankNo():"default";//支行名称recieveBankNo
						
						Integer type=shopInDTO.getRecieveAccountType();
						String merLvl=shopInDTO.getMerchantFeeId();
						String merStat="00";
						if(shopInDTO.getRecieveAccountType().equals(type)){
							pubOrPri="22";
							iDCardNo="000000000000000000";//长度必须是18位
						}else if(shopInDTO.getRecieveAccountType().equals(type)){
							pubOrPri="11";
							iDCardNo=shopInDTO.getPersonId();
						}
						MerchantUpdate merchantUpdate=MerchantUpdate.initialize(
								corpId, merName, groupId, corpType, bankCode, 
								bankAccountNm, bankAccountNo, phone, mobilePhone, sonBankName,
								lineBankNum, pubOrPri, iDCardNo, merLvl, detailed,merStat);
						PayResult payResult=IPayAPI.merchantUpdate(merchantUpdate);
					    if(!PayResult.SUCCESS.equals(payResult.getRespCode())){
					    	throw new ApplicationException(Rescode.FAIL,payResult.getRespCode()+"#"+payResult.getMsgTxt());
					    }
						return true;
				  }  else{
					  throw new ApplicationException(Rescode.FAIL,"地理位置解析异常");
					  
				  } 
			
		}

		@Override
		public YsShopOutDTO selectShopView(YsShopInDTO shopInDTO) throws ApplicationException {
			YsShopOutDTO shopOutDTO=new YsShopOutDTO();
			Shop shop=null;
			try {
			   shop=shopMapper.selectShopView(shopInDTO.getId());
			} catch (Exception e) {
				throw new ApplicationException(Rescode.FAIL,"查询详情异常");
			}
			try {
				PropertyCopyUtil.copyPropertiesExclude(shop, shopOutDTO);
			} catch (Exception e) {
				throw new ApplicationException(Rescode.FAIL,"属性复制异常");
			}
			shopOutDTO.setAgentName(shop.getAgent().getMerchantName());
			shopOutDTO.setTagentId(shop.getShopGroupRelation().getAgentId());
			shopOutDTO.setIndustryName(shop.getIndustryType().getName());
			shopOutDTO.setUserName(shop.getUserbase().getUsername()); 
			
			shopOutDTO.setMemberNum((shop.getStatisShop().getMemberNum()==null?0:shop.getStatisShop().getMemberNum()));
			shopOutDTO.setSumAmount(shop.getStatisShop().getSumAmount()==null?0:shop.getStatisShop().getSumAmount());
			shopOutDTO.setSumOrderNum((shop.getStatisShop().getSumOrderNum()==null?0:shop.getStatisShop().getSumOrderNum()));
			shopOutDTO.setSumProfit(shop.getStatisShop().getSumProfit()==null?0:shop.getStatisShop().getSumProfit());
			shopOutDTO.setThisAmount((shop.getStatisShop().getThisAmount()==null?0:shop.getStatisShop().getThisAmount()));
			shopOutDTO.setThisOrderNum((shop.getStatisShop().getThisOrderNum()==null?0:shop.getStatisShop().getThisOrderNum()));
			shopOutDTO.setThisProfit((shop.getStatisShop().getThisProfit()==null?0:shop.getStatisShop().getThisProfit()));
			
			
			String UserId=shop.getShopGroupRelation().getPayMerchantCode()+"";
			
			String GroupId=shop.getGroup().getPayGroupCode();
		    
		    Wallet wallet=walletService.selectShopWallet(UserId, GroupId, shop.getUserId());
		    shopOutDTO.setBalance(Long.valueOf(wallet.getCanBalance()));//余额 
		    shopOutDTO.setLockBalance(Long.valueOf(wallet.getCanFreezeBalance()));//锁定金额
		    
			shopOutDTO.setVarturelCardno(UserId);
			shopOutDTO.setAgentCreate(shop.getAgent().getGmtCreate());
			shopOutDTO.setAgentPhone(shop.getAgent().getPrincipalMobile());
			return shopOutDTO;
		}

		@Override
		public void saveShopType(YsShopInDTO shopInDTO) throws Exception {
			
			
			
			YsShopCar ysShopCar = new YsShopCar();
			ysShopCar.setShopId(shopInDTO.getShopId());
			YsShopCar ysShopCars = ysShopCarMapper.queryShopCar(shopInDTO.getShopId());
			ysShopCar.setGmtModified(new Date());
			ysShopCar.setShopType(shopInDTO.getShopType());
			if(shopInDTO.getIsInstall()!=null && shopInDTO.getIsInstall() !=0){
				ysShopCar.setIsInstall(shopInDTO.getIsInstall());
				ysShopCar.setInstallText(shopInDTO.getInstallText());
			}else{
				ysShopCar.setIsInstall(0);
				ysShopCar.setInstallText(null);
			}

			if(shopInDTO.getIsRefit()!=null && shopInDTO.getIsRefit() !=0){
				ysShopCar.setIsRefit(shopInDTO.getIsRefit());
				ysShopCar.setRefitText(shopInDTO.getRefitText());
			}else{
				ysShopCar.setIsRefit(0);
				ysShopCar.setRefitText(null);
			}

			if(shopInDTO.getIsCosmetology()!=null && shopInDTO.getIsCosmetology() !=0){
				ysShopCar.setIsCosmetology(shopInDTO.getIsCosmetology());
				ysShopCar.setCosmetologyText(shopInDTO.getCosmetologyText());
			}else{
				ysShopCar.setIsCosmetology(0);
				ysShopCar.setCosmetologyText(null);
			}
			if(shopInDTO.getIsRepair()!=null && shopInDTO.getIsRepair() !=0){
				ysShopCar.setIsRepair(shopInDTO.getIsRepair());
				ysShopCar.setRepairText(shopInDTO.getRepairText());
			}else{
				ysShopCar.setIsRepair(0);
				ysShopCar.setRepairText(null);
			}
			if(shopInDTO.getIsMaintain()!=null && shopInDTO.getIsMaintain() !=0){
				ysShopCar.setIsMaintain(shopInDTO.getIsMaintain());
				ysShopCar.setMaintainText(shopInDTO.getMaintainText());
			}else{
				ysShopCar.setIsMaintain(0);
				ysShopCar.setMaintainText(null);
			}


			if (ysShopCars.getCount()==0) {
				ysShopCar.setGmtCreate(new Date());
				ysShopCarMapper.insertSelective(ysShopCar);
			}else{
				ysShopCar.setId(ysShopCars.getId());
				ysShopCar.setGmtCreate(ysShopCars.getGmtCreate());
				ysShopCarMapper.updateByPrimaryKeySelective(ysShopCar);
			}

		}

		@Override
		public YsShopOutDTO goShopService(YsShopInDTO shopInDTO) {
			return shopMapper.goShopService(shopInDTO);
		}

		@Override
		public void updateShopServiceData(YsShopInDTO shopInDTO) {
			YsShopCar ysShopCar = new YsShopCar();
			YsShopCar ysShopCars = ysShopCarMapper.queryShopCar(shopInDTO.getShopId());
			ysShopCar.setId(ysShopCars.getId());
			ysShopCar.setGmtModified(new Date());
			ysShopCar.setInstallText(shopInDTO.getInstallText());
			ysShopCar.setRefitText(shopInDTO.getRefitText());
			ysShopCar.setCosmetologyText(shopInDTO.getCosmetologyText());
			ysShopCar.setRepairText(shopInDTO.getRepairText());
			ysShopCar.setMaintainText(shopInDTO.getMaintainText());
			
			ysShopCarMapper.updateByPrimaryKeySelective(ysShopCar);
			
		}

    @Override
    public YsShopOutDTO queryShopServiceType(YsShopInDTO shopInDTO) throws Exception {
		return ysShopCarMapper.queryShopServiceType(shopInDTO.getShopId());
    }

	@Override
	public YsShopOutDTO queryShopManage(YsShopInDTO shopInDTO) {
		return shopMapper.queryShopManage(shopInDTO);
	}

	@Override
	public YsShopOutDTO queryMerchantName(YsShopInDTO shopInDTO) throws Exception {
		return shopMapper.queryMerchantName(shopInDTO);
	}

	@Override
	public YsShopOutDTO queryName(YsShopInDTO shopInDTO) {

		return agentMapper.queryName(shopInDTO);
	}

	@Override
	public YsShopOutDTO queryShopRate(YsShopInDTO shopInDTO) {

		return shopMapper.queryShopRate(shopInDTO);
	}

	@Override
	public YsShopCar queryIdByShopId(YsShopInDTO shopInDTO) throws Exception {
		return ysShopCarMapper.queryIdByShopId(shopInDTO);
	}

	@Override
	public void insert(YsShopCar ysShopCar) throws Exception {
		ysShopCarMapper.insertSelective(ysShopCar);
	}

	@Override
	public YsShopOutDTO queryShopRateByshopId(YsShopInDTO shopInDTO) throws Exception {
		return shopMapper.queryShopRateByshopId(shopInDTO);
	}

//	@Override
//	public void editUpdateShopRate(YsShopInDTO shopInDTO) throws Exception {
//		YsShopCar ysShopCar = new YsShopCar();
//		ysShopCar.setId(shopInDTO.getId());
//		ysShopCar.setPreprofitRate(shopInDTO.getPreprofitRate());
//		ysShopCar.setPreprofitUpdateTime(new Date());
//		ysShopCarMapper.updateByPrimaryKeySelective(ysShopCar);
//	}

	@Override
	public Shop queryUserIdByShopId(Long id) {
		return shopMapper.queryUserIdByShopId(id);
	}


	@Override
	public void updateRate(YsShopCar ysShopCar) throws Exception {
		ysShopCarMapper.updateByPrimaryKeySelective(ysShopCar);
	}


}
